﻿//------------------------------------------------------------------------------
// <copyright file="RequestTemplateGenerator.cs" company="CommerceServer.net, Inc">
//    (c) 2012 CommerceServer.net, Inc. and its affiliates. All rights reserved.
// </copyright>
// <summary></summary>
//------------------------------------------------------------------------------ 
namespace CommerceServerContrib.CodeGeneration
{
    using CommerceServer.Foundation;
    using CommerceServerContrib.CodeGeneration.ConfigurationHelpers;
    using System.Collections.Generic;
    using System.Linq;

    public class RequestTemplateGenerator
    {
        private string targetConfigurationFilePath;
        private string channel;
        private string userLocale;
        private string userUILocale;

        public RequestTemplateGenerator(string configurationPath)
        {
            this.targetConfigurationFilePath = configurationPath;
        }

        public RequestTemplateGenerator(string configurationPath, string channel, string userLocale, string userUILocale)
        {
            this.targetConfigurationFilePath = configurationPath;
            this.channel = channel;
            this.userLocale = userLocale;
            this.userUILocale = userUILocale;
        }

        public List<RequestTemplateGroup> GetRequestTemplates()
        {
            using (var config = new FullConfigurationSwapper(this.targetConfigurationFilePath))
            {
                var templateGenerator = new CommerceServerRequestTemplateGenerator(this.channel, this.userLocale, this.userUILocale);
                var requestTemplates = templateGenerator.GetRequestTemplates();

                // Now group them so that Area so that they can be rendered in different static classes 
                var listOFGroup = new List<RequestTemplateGroup>();

                var listOFGroupName = this.GetListOfGroups(requestTemplates);
                foreach (string item in listOFGroupName)
                {
                    var group = new RequestTemplateGroup()
                    {
                        GroupName = item
                    };

                    group.RequestTemplates = requestTemplates.Where(r => r.Properties["Group"].ToString().Equals(item)).ToList();
                    listOFGroup.Add(group);
                }

                return listOFGroup;
            }
        }

        protected virtual HashSet<string> GetListOfGroups(List<CommerceEntity> requestTemplates)
        {
            var listOfGroups = new HashSet<string>();
            foreach (var item in requestTemplates)
            {
                listOfGroups.Add(item.Properties["Group"].ToString());
            }

            return listOfGroups;
        }
    }
}
